<!-- trademark -->
<template>
  <div>
    <el-card style="max-width: 100%">
      <template #header>
        <el-button
          color="#5cc2b3"
          type="success"
          round
          icon="Plus"
          v-has="`btn.Trademark.add`"
          @click="addTrademark"
        >
          添加品牌
        </el-button>
      </template>
      <el-table border style="width: 100%" :data="trademarkArr">
        <el-table-column label="序号" width="100" align="center" type="index" />
        <el-table-column label="品牌名称" align="center" prop="tmName" />
        <el-table-column label="品牌logo" align="center">
          <template #="{ $index, row }">
            <img :src="row.logoUrl" :style="{ width: '50%', height: '50%' }" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作" align="center">
          <template #="{ $index, row }">
            <el-button size="small" @click="updatedTrademark(row)">
              编辑
            </el-button>
            <el-button size="small" @click="removeTradeMark(row)" type="danger">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="pageNo"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            layout=" prev,pager, next,jumper,->,  sizes,total"
            :total="total"
            @current-change="getHasTrademark"
            @size-change="getHasTrademark"
          />
        </div>
      </template>
    </el-card>
    <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="!trademarkParams.id ? '添加品牌' : '修改品牌'"
      width="500"
      center
    >
      <el-form
        ref="formRef"
        style="padding: 20px"
        :model="trademarkParams"
        :rules="rules"
      >
        <el-form-item label="品牌名称:" label-width="100px" prop="tmName">
          <el-input v-model="trademarkParams.tmName" clearable />
        </el-form-item>
        <el-form-item label="品牌LOGO:" label-width="100px" prop="logoUrl">
          <!-- action路径注意下 -->
          <el-upload
            class="avatar-uploader"
            action="api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon
              v-else="!trademarkParams.logoUrl"
              class="avatar-uploader-icon"
            >
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirm">确定</el-button>
          <el-button type="primary" @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdatedTrademark,
  reqDeleteTrademark,
} from '../../../api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '../../../api/product/trademark/type'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { requiredNumber } from 'element-plus/es/components/table-v2/src/common.mjs'

let pageNo = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(1)
let trademarkArr = ref<Records>([])
let dialogFormVisible = ref<boolean>(false)
let formRef = ref()

// dialog对话框
let trademarkParams = reactive<any>({
  tmName: '',
  logoUrl: '',
})

onMounted(() => {
  getHasTrademark()
})

const getHasTrademark = async (pager = 1) => {
  pageNo.value = !trademarkParams.id ? pageNo.value : pager
  let res: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  trademarkArr.value = res.data.records
  total.value = res.data.total
}

const addTrademark = () => {
  nextTick(() => {
    formRef.value.clearValidate()
  })

  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
}

// 上传图片之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 上传图片成功时的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器

  trademarkParams.logoUrl = response.data
  console.log(trademarkParams.logoUrl)
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}

const confirm = async () => {
  //在你发请求之前,要对于整个表单进行校验
  //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
  await formRef.value.validate()
  let result: any = await reqAddOrUpdatedTrademark(trademarkParams)
  //添加|修改已有品牌
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    //弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获取已有全部的品牌数据
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    //关闭对话框
    dialogFormVisible.value = false
  }
}

const cancel = () => {
  dialogFormVisible.value = false
}

const validatorTmname = (rule: any, value: any, callback: any) => {
  if (value.trim().length < 2) {
    callback(new Error('品牌名称位数大于等于两位'))
  } else {
    callback()
  }
}

const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  // value是此图片的url
  if (value) {
    callback()
  } else {
    callback(new Error('输入图片'))
  }
  // console.log(value);
}

const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmname }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
// 修改一个品牌
const updatedTrademark = (row: any) => {
  nextTick(() => {
    formRef.value.clearValidate()
  })
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
  dialogFormVisible.value = true
  trademarkParams.id = row.id
}

// 删除一个品牌
const removeTradeMark = async (row: any) => {
  try {
    let data = row.id
    await reqDeleteTrademark(data)
    getHasTrademark()
    ElMessage({
      type: 'success',
      message: '删除产品成功',
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除产品失败',
    })
  }
}
</script>
<script lang="ts">
export default {
  name: 'trademark',
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
